import type {ProColumns} from '@ant-design/pro-components';
import {ProFormInstance, ProTable} from '@ant-design/pro-components';

import {
  loLogin,
  selectFailLoginList,
  chenxingCode,
  chenxingnewCode,
  cashbroCode,
  cashbroLogin,
  cxLogin,
  merchantList, tigerLogin, dosLogin, papaLogin, okrupeeLogin, prettyloanCode, prettyloanLogin, cxnewLogin
} from "@/services/bz/api";
import React, {useRef, useState} from "react";
import {Button, Image, message} from "antd";
import {ModalForm, ProFormText, ProForm} from "@ant-design/pro-form/es";
import {useRequest} from "@@/plugin-request/request";

export type TableListItem = {
  merchantCode: string;
  agentCode: string;
  orderNo: string;
  status: number;
  syncStatus: number;
};

export default () => {
  const restFormRef = useRef<ProFormInstance>();
  const formRef = useRef<ProFormInstance>();
  const [modalVisible, setModalVisible] = useState<boolean>(false);
  const [imageVisible, setImageVisible] = useState<boolean>(false);
  const [imageUrl, setImageUrl] = useState<String>("");
  const [papaKey, setPapaKey] = useState<String>("");
  const [merchantData, setMerchantData] = useState({});
  useRequest(merchantList, {
    onSuccess: (res) => {
      let data = {};
      //将拿到的返回值遍历
      res.list.map(item => {
        //使用接口返回值的id做为 代替原本的0，1
        data[item.merchantCode] = {
          //使用接口返回值中的overdueValue属性作为原本的text:后面的值
          text: item.merchantCode,
        };
      });
      setMerchantData(data);
      console.log("===", merchantData)
    },
  });

  const handleOk = (visible, record) => {
    if (visible) {
      if (record.merchantCode == "littleorange") {
        setImageUrl(`https://client.eivxmsffjgbin.com/api/verify_code/image_code.jpg?t=${new Date().getMilliseconds()}`)
      }else if (record.merchantCode == "papamoney"||record.merchantCode == "papamoney3") {
        const key = Math.round((Math.random() + 1) * 10000000000000000);
        setPapaKey(key)
        setImageUrl(`https://manage.pp-money.com/api/manage/auth/captcha?key=0.`+key)
      } else if (record.merchantCode == "chenxing") {
        chenxingCode().then((data) => {
          setImageUrl(data)
        })
      } else if (record.merchantCode == "chenxingnew") {
        chenxingnewCode().then((data) => {
          setImageUrl(data)
        })
      } else if (record.merchantCode == "cashbro"||record.merchantCode == "cashbroold") {
        cashbroCode().then((data) => {
          setImageUrl(data)
        })
      } else if (record.merchantCode == "prettyloan") {
        prettyloanCode(record.agentCode).then((data) => {
          setImageUrl(data)
        })
      }
    }
  };
  const columns: ProColumns<TableListItem>[] = [
    {
      title: '商户号',
      dataIndex: 'merchantCode',
      key: 'merchantCode',
      valueEnum: merchantData

    },
    {
      title: '坐席号',
      dataIndex: 'agentCode',
      search: false
    },
    {
      title: '账号',
      dataIndex: 'account',
      search: false
    },
    {
      title: '密码',
      dataIndex: 'password',
      search: false
    },
    {
      title: '登陆状态',
      dataIndex: 'loginStatus',
      search: false,
      render: (record) => {
        console.log("====",record)
        if (record == 2)
          return <div>
            <span>无效</span>
          </div>
        else
        return <div>
          <span>有效</span>
        </div>
      }
    },
    {
      title: '操作',
      key: 'option',
      width: 120,
      valueType: 'option',
      render: (text, record, _, action) => [
        <ModalForm
          title="Login Account"
          formRef={restFormRef}
          open={modalVisible}
          trigger={
            <Button
              type="primary"
              onClick={() => {
                if (record.merchantCode == "littleorange" || record.merchantCode == "chenxing"|| record.merchantCode == "chenxingnew" || record.merchantCode == "cashbro"|| record.merchantCode == "cashbroold"|| record.merchantCode == "prettyloan"|| record.merchantCode == "papamoney"|| record.merchantCode == "papamoney3") {
                  setImageVisible(false)
                }else {
                  setImageVisible(true)
                }
                setModalVisible(true);
              }}
            >
              Login
            </Button>
          }
          onVisibleChange={(visible) => handleOk(visible, record)}
          submitter={{
            searchConfig: {
              resetText: 'Close',
              submitText: 'Login',
            },
            submitButtonProps: {
              onClick: () => {
                let code=""
                if (restFormRef.current?.getFieldsValue().code != undefined){
                  code=restFormRef.current?.getFieldsValue().code
                }
                console.log("===", record.agentCode, code)
                if (record.merchantCode == "littleorange") {
                  loLogin(record.agentCode, code).then((res) => {
                    message.success(res)
                    console.log("===",)
                    restFormRef.current?.resetFields()
                    ref.current?.reload();
                  })
                } else if (record.merchantCode == "chenxing") {
                  cxLogin(record.agentCode, code).then((res) => {
                    message.success(res)
                    restFormRef.current?.resetFields()
                    ref.current?.reload();
                  })
                } else if (record.merchantCode == "chenxingnew") {
                  cxnewLogin(record.agentCode, code).then((res) => {
                    message.success(res)
                    restFormRef.current?.resetFields()
                    ref.current?.reload();
                  })
                } else if (record.merchantCode == "papamoney"||record.merchantCode == "papamoney3") {
                  papaLogin(record.agentCode, code,papaKey).then((res) => {
                    message.success(res)
                    restFormRef.current?.resetFields()
                    ref.current?.reload();
                  })
                } else if (record.merchantCode == "cashbro"||record.merchantCode == "cashbroold") {
                  cashbroLogin(record.agentCode, code).then((res) => {
                    message.success(res)
                    console.log("===",res)
                    restFormRef.current?.resetFields()
                    ref.current?.reload();
                  })
                } else if (record.merchantCode == "prettyloan") {
                  prettyloanLogin(record.agentCode, code).then((res) => {
                    message.success(res)
                    console.log("===",res)
                    restFormRef.current?.resetFields()
                    ref.current?.reload();
                  })
                } else if (record.merchantCode == "dos"||record.merchantCode == "everymoney"||record.merchantCode == "swiftcash"||record.merchantCode == "quickcash") {
                  dosLogin(record.agentCode, code).then((res) => {
                    message.success(res)
                    console.log("===",res)
                    restFormRef.current?.resetFields()
                    ref.current?.reload();
                  })
                } else if (record.merchantCode == "sareecash" ||record.merchantCode == "pagli" ||record.merchantCode == "drisana" ||record.merchantCode == "asher" || record.merchantCode == "rupeebag"|| record.merchantCode == "creditmuga"|| record.merchantCode == "puttu"|| record.merchantCode == "idliloanin"|| record.merchantCode == "relax"|| record.merchantCode == "rupeeyaaron"|| record.merchantCode == "poppins"|| record.merchantCode == "walnutsloan"|| record.merchantCode == "idli"|| record.merchantCode == "naanloan"|| record.merchantCode == "korma"|| record.merchantCode == "popinsloan"|| record.merchantCode == "selina"|| record.merchantCode == "tenzin"|| record.merchantCode == "rupeedidi"|| record.merchantCode == "pravin") {
                  tigerLogin(record.agentCode, code).then((res) => {
                    message.success(res)
                    console.log("===",)
                    restFormRef.current?.resetFields()
                    ref.current?.reload();
                  })
                } else if (record.merchantCode == "okrupee") {
                  okrupeeLogin(record.agentCode, code).then((res) => {
                    message.success(res)
                    console.log("===",)
                    restFormRef.current?.resetFields()
                    ref.current?.reload();
                  })
                }


              },
            },
          }}
          onFinish={async (values) => {
            console.log(values);
            return true;
          }}
        >

          <div hidden={imageVisible}>
            <ProForm.Group>
              <Image
                width={200}
                style={{marginBottom: "20px"}}
                src={imageUrl}
              />

              <Button
                type="primary"
                onClick={() => {
                  if (record.merchantCode == "littleorange") {
                    setImageUrl(`https://client.eivxmsffjgbin.com/api/verify_code/image_code.jpg?t=${new Date().getMilliseconds()}`)
                  } else if (record.merchantCode == "papamoney"||record.merchantCode == "papamoney3") {
                    const key = Math.round((Math.random() + 1) * 10000000000000000);
                    setPapaKey(key)
                    setImageUrl(`https://manage.pp-money.com/api/manage/auth/captcha?key=0.`+key)
                  } else if (record.merchantCode == "chenxing") {
                    chenxingCode().then((data) => {
                      setImageUrl(data)
                    })
                  } else if (record.merchantCode == "chenxingnew") {
                    chenxingnewCode().then((data) => {
                      setImageUrl(data)
                    })
                  } else if (record.merchantCode == "cashbro"||record.merchantCode == "cashbroold") {
                    cashbroCode().then((data) => {
                      setImageUrl(data)
                    })
                  } else if (record.merchantCode == "prettyloan") {
                    prettyloanCode(record.agentCode).then((data) => {
                      setImageUrl(data)
                    })
                  }
                }}
              >
                刷新
              </Button>
            </ProForm.Group>

          </div>


          <ProFormText
            width="md"
            name="code"
            label="Code"
            tooltip="pls input code"
            placeholder="input code"
          />

        </ModalForm>
      ]
    }
  ];
  const ref = useRef<ProFormInstance>();
  return (
    <div>
      <ProTable<TableListItem>
        actionRef={ref}
        style={{
          margin: '16px',
        }}
        columns={columns}
        request={async (params: any) => {
          console.log("===", params)
          let code = null;
          if (params.merchantCode != undefined) {
            code = params.merchantCode
          }
          let response = await selectFailLoginList(code);
          console.log(1231, response);
          return {data: response.data == null ? [] : response.data.list};
        }}
        rowKey="key"
        pagination={{
          showSizeChanger: true,
        }}
        search={{
          labelWidth: 'auto',
        }}
        options={false}
        headerTitle=" "
        revalidateOnFocus={false}

      />
    </div>

  );
};
